<template>
    <view class="content">
        <van-popup position="bottom" @click-overlay="closePopup" :show="JOpopup" round z-index=104
            custom-style="width: 100%;background:#ffffff;overflow: hidden; height:70%">
            <view class="popup-content">

                <view class="popup-main">
                    <view style="display: flex; justify-content: space-between;align-items: center; padding-left: 48rpx;">
                        <view class="goodsSortTitle"> {{ title }}</view>
                        <van-icon name="cross" color="#FFFFFF" size="15" @click="closePopup" />
                    </view>
                    <scroll-view :refresher-enabled="false" class="scroll-content" scroll-y :lower-threshold="80" show-scrollbar="false">

                        <!-- 全部分类 -->
                        <view class="JOpopup-content sidebar_box" v-if="popupBiaoshi === 1">

                            <view class="sidebar">
                                <view class="sidebar-item" :class="{active:activeKey===index}"  v-for="(item, index) in sidebarList" :key="index" :id="item.id" :title="item.cateName" @click="onChangeSidebar(item,index,$event)">
                                    {{item.name}} 
                                    <span v-if="getSelectedCount(item)" style="margin-left: 6rpx;" class="count-badge"> ({{ getSelectedCount(item) }})</span>
                                </view>
                            </view>
                            <view class="sidebar_content">
                                <view class="goods-box-content-title" v-for="(item, index) in secondCategoryList" :key="index"
                                :id="item.id" @click="selectItem(item,index,$event)">
                                    <view class="title" >{{ item.name }}</view>
                                    <view class="selected" v-if="item.isTag && item.isTag===true"> <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/isSelected.png" alt="" style="width: 24rpx;height: 18rpx;"> </view>
                                </view>
                            </view>
                        </view>
                        <van-toast id="van-toast" />
                    </scroll-view>
                </view>
                <view class="goodsAction nav_box">
                    <van-goods-action>
                        <van-goods-action-icon class="custom-icon" icon="replay" text="重置" @click="onClickReplay">
                            <!-- <img slot="icon" src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/reset.png" alt="" style="width:14rpx; height:14rpx;"> -->
                        </van-goods-action-icon>
                        <van-goods-action-button color="#FF6203" text="确定" @click="onConfirm" />
                    </van-goods-action>
                </view>
            </view>
        </van-popup>
    </view>
</template>

<script>
import {queryCategoryTreeApi} from '@/api/mall'

import Toast from '@/wxcomponents/vant/toast/toast'
export default {
    props: {
        JOpopup: {
            type: Boolean,
            default: () => false
        },
        roleName: {
            type: String,
            default: () => ''
        },
        popupBiaoshi:{
            type: Number,
            default: () => 0
        }
    },
    data () {
        return {
            curS:0,
            curSName:'',
            date: '',
            show: true,
            title: '全部分类',
            option: {},
            url: '',
            stepperValue:1,

            sidebarList:[
                { id:0, cateName:'美食' },
                { id:1, cateName:'家居' },
                { id:2, cateName:'日化' },
                { id:3, cateName:'户外' },
                { id:4, cateName:'临期' }
            ],
            secondCategoryList: [
                // {
                //     // 名称
                //     cateName: '休闲零食',
                //     // id，作为匹配选中状态的标识
                //     goodsId: 1,

                // },
                // {
                //     cateName: '茶咖冲饮',
                //     goodsId: 2,
                // },

                // {
                //     cateName: '肉食海鲜',
                //     goodsId: 3,
                // },
                // {
                //     cateName: '营养谷物',
                //     goodsId: 4,
                // },
                // {
                //     cateName: '饼干糕点',
                //     goodsId: 5,
                // },
            ],
            mainActiveIndex: 0,   //左侧 选项索引
            activeId: [],   /// 右侧 选项中 ids数组
            max: 2, //右侧最大选中数
            items: [
                {
                    itemId:1,
                    // 导航名称
                    text: '美食',
                    // 导航名称右上角徽标，1.5.0 版本开始支持
                    badge: 3,
                    // 是否在导航名称右上角显示小红点，1.5.0 版本开始支持
                    dot: true,
                    // 禁用选项
                    disabled: false,
                    // 该导航下所有的可选项
                    children: [
                        {
                            // 名称
                            text: '休闲零食',
                            // id，作为匹配选中状态的标识
                            id: 1,
                            // 禁用选项
                            // disabled: true,
                        },
                        {
                            text: '茶咖冲饮',
                            id: 2,
                        },
                    
                        {
                            text: '肉食海鲜',
                            id: 3,
                        },
                        {
                            text: '营养谷物',
                            id: 4,
                        },
                        {
                            text: '饼干糕点',
                            id: 5,
                        },
                    ],
                },
                {   
                    itemId:2,
                    // 导航名称
                    text: '家居',
                    // 导航名称右上角徽标，1.5.0 版本开始支持
                    badge: 3,
                    // 是否在导航名称右上角显示小红点，1.5.0 版本开始支持
                    // dot: true,
                    // 禁用选项
                    disabled: false,
                    // 该导航下所有的可选项
                    children: [
                        {
                            // 名称
                            text: '休闲零食',
                            // id，作为匹配选中状态的标识
                            id: 1,
                            // 禁用选项
                            disabled: true,
                        },
                        {
                            text: '茶咖冲饮',
                            id: 2,
                        },
                    
                    ],
                },
                {
                    itemId:3,
                    // 导航名称
                    text: '日化',
                    // 导航名称右上角徽标，1.5.0 版本开始支持
                    badge: 3,
                    // 是否在导航名称右上角显示小红点，1.5.0 版本开始支持
                    // dot: true,
                    // 禁用选项
                    disabled: false,
                    // 该导航下所有的可选项
                    children: [
                        {
                            // 名称
                            text: '休闲零食',
                            // id，作为匹配选中状态的标识
                            id: 1,
                            // 禁用选项
                            disabled: true,
                        },
                        {
                            text: '茶咖冲饮',
                            id: 2,
                        },
            
                        {
                            text: '肉食海鲜',
                            id: 3,
                        },
                        {
                            text: '营养谷物',
                            id: 4,
                        },
                        {
                            text: '饼干糕点',
                            id: 5,
                        },
                    ],
                },
                {
                    itemId:4,
                    // 导航名称
                    text: '户外',
                    // 导航名称右上角徽标，1.5.0 版本开始支持
                    // badge: 3,
                    // 是否在导航名称右上角显示小红点，1.5.0 版本开始支持
                    dot: true,
                    // 禁用选项
                    disabled: false,
                    // 该导航下所有的可选项
                    children: [  ],
                },
                {
                    itemId:5,
                    // 导航名称
                    text: '临期',
                    // 导航名称右上角徽标，1.5.0 版本开始支持
                    badge: 3,
                    // 是否在导航名称右上角显示小红点，1.5.0 版本开始支持
                    // dot: true,
                    // 禁用选项
                    disabled: false,
                    // 该导航下所有的可选项
                    children: []
    
                },
            ],
            list: [], // ----------------待选列表, 部门+人员子级 children嵌套
            flowList: [], // 正在处理人员,用于禁选

            userListAll: [], // 所有子级项数组,用来筛选
            mainDept: null, // 当前用户部门信息
            popupHeight:'460',
            selectedRows:[],
            selectedRowKeys:[],
            activeKey:0

        }
    },

    computed: {
        // 用来返回到父页面
        activeList() {
            // let selectedData = [];
            // if (Array.isArray(this.activeId)) {
            //     selectedData = this.activeId.map((id) => {
            //         // 通过 id 查找对应的数据
            //         return this.userListAll.find((data) => data.id == id);
            //     });
            // }
            // return selectedData;
        },
        // 过滤后的右侧人员列表
        // filterUserList() {
        //     return this.filterNewUserList(this.list, this.searchName);
        // },
    },
    filters: {
        // 过滤选择人员
        newUserList(list, searchName) {
            let arr = [];
            if (searchName != "") {
                list.forEach((item1, index1) => {
                    arr.push({
                        text: item1.text,
                        children: [],
                    });
                    item1.children.forEach((item2) => {
                        if (item2.text.toLowerCase().includes(searchName.toLowerCase())) {
                            arr[index1].children.push({
                                id: item2.id,
                                disabled: item2.disabled,
                                text: item2.text,
                            });
                        }
                    });
                });
                return arr;
            } else {
                return list;
            }
        },
    },


  watch:{
    secondCategoryList: {
        handler(val) {
            console.log(val)
            var i = 0
            this.secondCategoryList.forEach(item => {
                if (item.isTag === true) {
                    i++
                }
            })
        },
        deep: true
        },
        selectedRowKeys: {
            handler (val) {
                console.log(val, 'selectedRowKeys')
                if (val.length > 0) {
                    this.isShowBlue = true // 标记为正常的按钮  深蓝色
                } else {
                    this.isShowBlue = false // 标记为正常的按钮  浅蓝色
                }

            }
        },
        selectedRows: {
            handler (val) {
                console.log(val, 'selectedRows')
            }
        }


    },
    onLoad () {
        if (this.popupBiaoshi===0) {
            this.title = '商品排序'
        } else if (this.popupBiaoshi===2) {
            this.title = '价格区间'
        }else{
            this.title = '全部分类'
        }
    },
    onReady () {
        // this.init();
        // this.secondCategoryList.forEach((item,index)=>{
        //     this.$set(item,'isTag',false)
        // })
        this.getCategoryTreeData()
    },

    methods: {

        // 关闭弹窗
        closePopup() {
            this.$emit('closeJOPopup')
        },

        // 重置
        onClickReplay() {
            this.selectedRowKeys = []
            this.selectedRows = []
            this.sidebarList.forEach(cate => {
                cate.secondCategoryList?.forEach(child => {
                    this.$set(child, 'isTag', false);
                });
            });
        },

        // 确定    分类+价格区间
        onConfirm() {
            this.$emit('confirm', {
                keys: this.selectedRowKeys,
                data: this.selectedRows
            });
            Toast('选择成功');
            this.closePopup();
        },

        // 确定
        onConfirm() {
            this.$emit("input", this.activeList);
            this.$emit("onConfirm", this.activeList);
        },
     
        onChangeSidebar(item, val, e) {
            this.activeKey = val
            console.log(this.activeKey,item, val, e, 'e sideBar')
            const currentChildren = item.children?.length ? item.children : [];
            this.secondCategoryList = currentChildren.map((child) => {
                return {
                    ...child,
                    // 保持选中状态
                    isTag: this.selectedRowKeys.includes(child.id),
                };
            });
            // this.sidebarList.forEach((item, index) => {
            //     if (val === index) {
            //         this.secondCategoryList = item.children || []
            //         this.secondCategoryList.forEach((item, index) => {
            //             this.$set(item, 'isTag', this.selectedRowKeys.includes(child.id))
            //         })
            //     }
            // })
        },
        selectItem(ele, val, e) {
            const index = this.selectedRowKeys.indexOf(ele.id);
            if (index > -1) {
                // 取消选中
                this.selectedRowKeys.splice(index, 1);
                this.selectedRows.splice(index, 1);
            } else {
                // 新增选中
                this.selectedRowKeys.push(ele.id);
                this.selectedRows.push(ele);
            }
            // 更新视图状态
            this.$set(ele, 'isTag', !ele.isTag);
            // 强制更新视图
            this.$forceUpdate();
        },

        getSelectedCount(category) {
            const childrenIds = category.children?.map(c => c.id) || [];
            return this.selectedRowKeys.filter(id => childrenIds.includes(id)).length;
        },
        // 接口

        // 一二级分类树
        async getCategoryTreeData() {
            return new Promise((resolve, reject) => {
                queryCategoryTreeApi(1).then((res) => {
                    if (res.code === 200) {
                        console.log(res.data, 'res', res.message)
                        this.sidebarList = res.data
                        this.sidebarList.forEach((ele, index) => {
                          if(this.activeKey === index){
                            this.secondCategoryList = ele.children || []
                            this.secondCategoryList.forEach((item, index) => {
                                this.$set(item, 'isTag', false)
                            })
                          }
                        })
                    }else{
                        reject(res)
                    }
                })
            })
        }

    },

}
</script>
<style lang="scss" scoped>


// ::v-deep .van-button__text {
//     display: flex !important;
//     flex-direction: column !important;
// }
// 最外层
.content {
    // display: flex;
    // flex-direction: column;
    // box-sizing: border-box;
    // overflow-y: auto;
    // z-index: -2;
    // scrollbar-width: none;
    /* 针对Firefox */
}
// 滚动
.scroll-content {
    flex: 1;
    height: 1rpx;
}
// 提示框
.popup-content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding-top: 48rpx;
    padding-bottom: calc(0rpx + env(safe-area-inset-bottom));
    font-size: 24rpx;
    border-radius: 16rpx;
    overflow: hidden;
    // height:50%;


    .popup-main{
        padding-right:48rpx;
        height:100%;
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
    }


    .goodsSortTitle{
        // font-weight: 500;
        font-size: 40rpx;
        text-align: left;
        color: #111111;
        line-height: 40rpx;
        padding-bottom: 12rpx;

    }


    .JOpopup-content {
       
    }


// 全部分类
    // 加入购物车按钮
    .goodsAction {
        // margin-top: 22rpx;
        // width: calc(100% - 48rpx);
        text-align: center;
        // background-color: aquamarine;
        height: 144rpx;
    }
}

.sidebar_box {
    overflow: hidden;
    display: flex;
    padding-top: 22rpx;
}
.sidebar{
    width: 210rpx !important;
    min-height: 576rpx;
    display: flex;
    flex-direction: column;
    background-color: #f9f9f9;
}
.sidebar-item{
    font-size: 28rpx;
    height: 110rpx;
    line-height: 110rpx;
    text-align: center;
    color: #333333;
    background-color: #f9f9f9;

    &.active{
        font-weight: bolder;
        font-size:32rpx;
        text-align: center;
        color: #111111;
        background-color: #ffffff;
    }
}

.sidebar_content{
    width: calc(100% - 304rpx);
    margin-left:94rpx;
    overflow: hidden;
    height: 100vh;
    display: flex;
    flex-direction: column;
    // justify-content: center;
    // vertical-align: middle;
    // background-color: palegoldenrod;
}

// 商品分类模块

.goods-box-content-title{
    width: 100%;
    padding-bottom:59rpx ;
    line-height: 28rpx;
    font-size: 28rpx;
    text-align: left;
    color: #333333;
    display: flex;
    justify-content: space-between;
    align-items: center;
    // background-color: aqua;
}

::v-deep .van-goods-action, .van-goods-action--safe{
    border-top: 1px solid #f9f9f9 !important;
}

::v-deep .van-cell {
    border: 1rpx solid #888888 !important;
}

::v-deep .van-cell--hover .hover-class{
    border: 1rpx solid #888888;
}


// sidebar
::v-deep .sidebar_box .van-sidebar{
    width:210rpx !important;
    height: 100vh;
    background-color: #F7F7F7;
}
.main .van-sidebar-item--selected{
    border-color: var(--main-color) !important;
    background-color: white;
}
// 未选中的样式
::v-deep .sidebar_box .van-sidebar-item {
    border-left:none !important;
    font-size: 28rpx;
    line-height: 28rpx;
    text-align: center;
    color: #333333;
    border: none !important;
    background-color: transparent;
}
// 选中的样式
::v-deep .sidebar_box .van-sidebar-item--selected{
    border-color: var(--main-color) !important;
    background-color: white;
    font-weight: bolder;
    line-height: 32rpx;
    font-size:32rpx;
    text-align: center;
    color: #111111;
    background-color: #ffffff;
    //   border-color: transparent !important;
}
/* 添加计数徽章样式 */
.count-badge {
    color: #FF6203;
    margin-left: 8rpx;
    font-size: 24rpx;
}

/* 确保选中状态可见 */
.selected img {
    display: inline-block !important;
}
</style>

